﻿using InfluxDB.Client.Core;

using System.Text;

namespace ConsoleApp1.Test
{
    public class Class0
    {
        void Test10()
        {
            var list1 = new List<string>() { "1", "2", "3" };
            var list2 = new List<string>() { "1", "2", "6" };
            var result = list1.Any(x => list2.Any(y => y == x));

            XTrace.WriteLine(result.ToString());
        }
        void Test9()
        {
            UTC();

            //如果Run方法无异常正常执行,那么程序无法得知其状态机什么时候执行完毕
            //Run();

            //因为在此进行await,所以主程序知道什么时候状态机执行完成
            //await RunAsync();


            //RunAsync1();

            /*
            var _MERGE_NUM = 0;
            var _LAY_NUM = 0;
            var _RULER_NUM = 0;
            var _HAND_HEIGHT = 0;

            var _MODE_PARAMETER_CHECK = GET_MODE_PARAMETER(616, 115, 433, 24, out _MERGE_NUM, out _LAY_NUM, out _RULER_NUM, out _HAND_HEIGHT);


            //GetAQM("1TE65NKTCN1B03ACFLY9101");

            string pw = null;
            pw = pw + "1";
            //var abcd = "0123456789".IndexOf("u");

            //var newSN = "1TE7547TCNWB0LA4XLY1101";
            //var year = newSN.Substring(14, 1);
            //var month = newSN.Substring(15, 1);
            //var day = newSN.Substring(16, 1);
            //var printDate = GetPrintYear(year) + "年" + GetPrintMonth(month) + "月" + GetPrintDay(day) + "日";
            List<string> abc = new List<string>() { "a", "b", "c", string.Empty };
            var def = "def";

            //if (def.StartsWith(null))
            //{

            //}

            var ghl = abc.FirstOrDefault(x => def.StartsWith(x));

            //Thread t = new Thread((ThreadStart)delegate
            //{
            //    throw new Exception("非窗体线程异常");
            //});
            //t.Start();

            */
        }
        void UTC(string startTime = "2023-08-16T03:02:53.593Z")
        {
            XTrace.WriteLine(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ"));

        }

        static int ObjToInt(object thisValue)
        {
            int result = 0;
            if (thisValue == null)
            {
                return 0;
            }

            if (thisValue is Enum)
            {
                return (int)thisValue;
            }

            if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out result))
            {
                return result;
            }

            return result;
        }

        static async void Run()
        {
            //      由于方法返回的为void,所以在调用此方法时无法捕捉异常,使得进程崩溃
            throw new Exception("异常了");
            await Task.Run(() => { });

        }
        static async Task RunAsync()
        {
            //      因为此异步方法返回的为Task,所以此异常可以被捕捉
            throw new Exception("异常了");
            await Task.Run(() => { });

        }

        static async Task<string> RunAsync1()
        {
            await RunAsync2();
            return "OK";
        }

        static async Task<string> RunAsync2()
        {

            //try
            //{

            //      因为此异步方法返回的为Task,所以此异常可以被捕捉
            //throw new Exception("异常了");
            //await Task.Run(() => { });

            //创建HttpWeb请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://172.16.110.245:10070/api/AndonDownload");
            //创建HttpWeb相应
            HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync());

            //获取response的流
            Stream receiveStream = response.GetResponseStream();

            //使用streamReader读取流数据
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            Console.WriteLine("Response stream received.");
            Console.WriteLine(readStream.ReadToEnd());
            response.Close();
            readStream.Close();


            //}
            //catch (Exception ex)
            //{
            //    throw ex;
            //}

            return "OK";

        }

        static string GetPrintYear(string str)
        {
            var re = "";
            switch (str)
            {
                case "Z":
                    re = "2001";
                    break;
                case "Y":
                    re = "2002";
                    break;
                case "W":
                    re = "2003";
                    break;
                case "V":
                    re = "2004";
                    break;
                case "U":
                    re = "2005";
                    break;
                case "T":
                    re = "2006";
                    break;
                case "S":
                    re = "2007";
                    break;
                case "R":
                    re = "2008";
                    break;
                case "Q":
                    re = "2009";
                    break;
                case "P":
                    re = "2010";
                    break;
                case "N":
                    re = "2011";
                    break;
                case "M":
                    re = "2012";
                    break;
                case "L":
                    re = "2013";
                    break;
                case "K":
                    re = "2014";
                    break;
                case "J":
                    re = "2015";
                    break;
                case "H":
                    re = "2016";
                    break;
                case "G":
                    re = "2017";
                    break;
                case "F":
                    re = "2018";
                    break;
                case "E":
                    re = "2019";
                    break;
                case "D":
                    re = "2020";
                    break;
                case "C":
                    re = "2021";
                    break;
                case "B":
                    re = "2022";
                    break;
                case "A":
                    re = "2023";
                    break;
                case "9":
                    re = "2024";
                    break;
                case "8":
                    re = "2025";
                    break;
                case "7":
                    re = "2026";
                    break;
                case "6":
                    re = "2027";
                    break;
                case "5":
                    re = "2028";
                    break;
                case "4":
                    re = "2029";
                    break;
                case "3":
                    re = "2030";
                    break;
                case "2":
                    re = "2031";
                    break;
                case "1":
                    re = "2032";
                    break;
                case "0":
                    re = "2033";
                    break;
                default:
                    re = "1";
                    break;
            }
            return re;
        }

        static string GetPrintMonth(string str)
        {
            var re = "";
            switch (str)
            {
                case "1":
                    re = "1";
                    break;
                case "A":
                    re = "2";
                    break;
                case "2":
                    re = "3";
                    break;
                case "B":
                    re = "4";
                    break;
                case "3":
                    re = "5";
                    break;
                case "C":
                    re = "6";
                    break;
                case "4":
                    re = "7";
                    break;
                case "D":
                    re = "8";
                    break;
                case "5":
                    re = "9";
                    break;
                case "E":
                    re = "10";
                    break;
                case "6":
                    re = "11";
                    break;
                case "F":
                    re = "12";
                    break;
                default:
                    re = "1";
                    break;
            }
            return re;
        }

        static string GetPrintDay(string str)
        {
            var re = "";
            switch (str)
            {
                case "1":
                    re = "1";
                    break;
                case "2":
                    re = "2";
                    break;
                case "3":
                    re = "3";
                    break;
                case "4":
                    re = "4";
                    break;
                case "5":
                    re = "5";
                    break;
                case "6":
                    re = "6";
                    break;
                case "7":
                    re = "7";
                    break;
                case "8":
                    re = "8";
                    break;
                case "9":
                    re = "9";
                    break;
                case "A":
                    re = "10";
                    break;
                case "B":
                    re = "11";
                    break;
                case "C":
                    re = "12";
                    break;
                case "D":
                    re = "13";
                    break;
                case "E":
                    re = "14";
                    break;
                case "F":
                    re = "15";
                    break;
                case "G":
                    re = "16";
                    break;
                case "H":
                    re = "17";
                    break;
                case "J":
                    re = "18";
                    break;
                case "K":
                    re = "19";
                    break;
                case "L":
                    re = "20";
                    break;
                case "M":
                    re = "21";
                    break;
                case "N":
                    re = "22";
                    break;
                case "P":
                    re = "23";
                    break;
                case "Q":
                    re = "24";
                    break;
                case "R":
                    re = "25";
                    break;
                case "S":
                    re = "26";
                    break;
                case "T":
                    re = "27";
                    break;
                case "U":
                    re = "28";
                    break;
                case "V":
                    re = "29";
                    break;
                case "W":
                    re = "30";
                    break;
                case "Y":
                    re = "31";
                    break;
                default:
                    re = "1";
                    break;
            }
            return re;
        }

        Dictionary<string, string> GetPanasonicSeqInfo(DateTime snDate)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            double tt = (snDate.Month / 2) + 0.1;
            int m = (int)Math.Ceiling(tt);
            dic.Add("$P_M$", m.ToString());
            List<int> intM1 = new List<int>() { 1, 3, 5, 7, 9, 11 };
            List<int> intM2 = new List<int>() { 2, 4, 6, 8, 10, 12 };
            int day = 0;
            if (intM1.Contains(snDate.Month))
            {
                if (snDate.Day < 11)
                {
                    day = 1;
                }
                else if (snDate.Day < 21)
                {
                    day = 2;
                }
                else
                {
                    day = 3;
                }
                dic.Add("$P_D$", day.ToString());
            }
            if (intM2.Contains(snDate.Month))
            {
                if (snDate.Day < 11)
                {
                    day = 4;
                }
                else if (snDate.Day < 21)
                {
                    day = 5;
                }
                else
                {
                    day = 6;
                }
                dic.Add("$P_D$", day.ToString());
            }
            string y = snDate.ToString("yy").Substring(1, 1);
            dic.Add("$P_DATE_3$", y + m.ToString() + day.ToString());
            return dic;
        }

        void Test8()
        {
            var _POSTS = new List<string> { "底座装箱", "tcon安装", "夹子安装", "理线" };

            string[] orderArr = new string[] { "tcon安装", "tcon锁固", "壁挂安装", "主板安装", "主板锁固", "壁挂锁固", "FFC线插装", "插线", "扬声器安装", "遥控安装插线", "理线", "整机信息采集", "后壳准备", "后壳锁固", "整机立直", "夹子安装", "通道检验", "电性能总检", "面板保护胶带贴附", "电源线整理", "整机外观检", "防破片纸板贴附", "整机下机", "整机套箱", "标签贴附", "整机泡沫封箱", "附件装箱", "底座装箱" };

            _POSTS = _POSTS.OrderBy(e =>
            {
                var index = 0;
                index = Array.IndexOf(orderArr, e);
                if (index != -1) { return index; }
                else
                {
                    return int.MaxValue;
                }
            }).ToList();

            _POSTS.ForEach(p =>
            {
                XTrace.WriteLine(p);
            });
        }

        void Test7()
        {
            List<int> listA = new List<int> { 1, 2, };

            List<int> listB = null;// new List<int> { 2, 3 };

            List<int> Result1 = listA.Union(listB).ToList<int>();          //剔除重复项 
            List<int> Result2 = listA.Concat(listB).ToList<int>();        //保留重复项

            XTrace.WriteLine(Result1.ToJson());

            XTrace.WriteLine(Result2.ToJson());
        }

        void Test6()
        {

            var svr = new NetServer
            {
                Port = 1234,
                Log = XTrace.Log
            };

            svr.Received += Svr_Received;
            svr.Add<StandardCodec>();
            //svr.Add<EchoHandler>();
            // 打开原始数据日志
            var ns = svr.Server;
            ns.LogSend = true;
            ns.LogReceive = true;


            svr.Start();

            MessageActor._NetServer = svr;
        }

        void Svr_Received(object sender, ReceivedEventArgs e)
        {
            var pk = e.Message as Packet;

            XTrace.WriteLine("Svr_Received-收到：{0}", pk?.ToStr());

            var actor = new MessageActor();
            actor.Tell(pk?.ToStr());
            // 等待最终完成
            actor.Stop();
        }


        async void Test5()
        {
            //MqttClient _mc = null;

            //if (_mc == null || !_mc.IsConnected)
            //{
            //    _mc = new MqttClient()
            //    {
            //        Log = XTrace.Log,
            //        Server = "tcp://127.0.0.1:51883",
            //        ClientId = $"{Environment.MachineName}_SUB_{Environment.ProcessId}",
            //        //UserName = "admin",
            //        //Password = "admin",
            //    };

            //    await _mc.ConnectAsync();
            //}

            //if (_mc?.IsConnected ?? false)
            //{
            //    _mc.Received += Mc_Received;
            //    var rt = await _mc.SubscribeAsync("/test");

            //    //var rt = await mc.SubscribeAsync("/test");
            //    //var rt = await mc.SubscribeAsync("devices/AnalogDevice1/telemetry");
            //}
        }

        void Mc_Received(object? sender, NewLife.EventArgs<NewLife.MQTT.Messaging.PublishMessage> e)
        {
            var pm = e.Arg;
            var msg = pm.Payload.ToStr();

            XTrace.WriteLine("ConsoleApp1_消费消息：[{0}] {1}", pm.Topic, msg);
        }


        void Test4()
        {
            var oldBar = "1TE43J6TCNWB0BB9KHK2661";
            string oldDateSecretCode = oldBar.Substring(14, 3);//原日期暗码
            string oldDateStr = GetYearNo(oldDateSecretCode.Substring(0, 1)) + "-" + GetMonthNo(oldDateSecretCode.Substring(1, 1)) + "-" + GetDayNo(oldDateSecretCode.Substring(2, 1));//解密
            var currentDate = Convert.ToInt32(Convert.ToDateTime(oldDateStr).ToString("yyyyMMdd"));
        }

        string GetYearNo(string year)
        {
            string[] years = { "Z", "Y", "W", "V", "U", "T", "S", "R", "Q", "P", "N", "M", "L", "K", "J", "H", "G", "F", "E", "D", "C", "B", "A", "9", "8", "7", "6", "5", "4", "3", "2", "1" };
            int index = 0;
            foreach (string str in years)
            {
                index++;
                if (str == year)
                {
                    break;
                }
            }
            //现取时间 add hairui @2020-12-19 9:5:18 
            int currentDate = DateTime.Now.ToString("yyyyMMdd").ToInt();
            int iyear = Convert.ToInt32(currentDate.ToString().Substring(0, 4));
            int pdate = Math.Abs((iyear - 2000)) % 32;
            return (index % 32 + ((iyear - 2000) / 32) * 32 + 2000).ToString();
        }
        string GetMonthNo(string month)
        {
            string[] months = { "A", "B", "C", "D", "E", "F" };
            int index = 0;
            bool flag = false;
            foreach (string str in months)
            {
                index++;
                if (str == month)
                {
                    flag = true;
                    break;
                }
            }
            if (!flag)
            {
                return (int.Parse(month) * 2 - 1).ToString();
            }
            else
            {
                return (index * 2).ToString();
            }
        }
        string GetDayNo(string day)
        {
            string[] days = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "Y" };
            int index = 0;
            foreach (string str in days)
            {
                index++;
                if (str == day)
                {
                    break;
                }
            }
            return index.ToString();
        }

        void Test3()
        {
            var students = new List<Student>() { new Student() { Id = 1, Name = "张三", Age = 30 }, new Student() { Id = 2, Name = "李四", Age = 31 } };

            foreach (var item in students)
            {
                item.Name = "-" + item.Name;
            }

            XTrace.WriteLine(students.ToJson());
        }


        void Test2()
        {
            List<int> ints = new List<int>() { 1, 2, 3 };

            var intsJson = ints.ToJson();

            XTrace.WriteLine(intsJson);

            var abc = intsJson.ToJsonEntity<List<int>>();

            XTrace.WriteLine(abc.ToJson());

        }

        void Test1()
        {
            string[] array = new[] { "id", "name", "age" };

            var abc = string.Join(@""",""", array);

            XTrace.WriteLine(abc);

        }

        /// <summary>
        /// 根据序列号获取安全码
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        static string GetAQM(string barcode)
        {
            string IStr = "ABCDEFGHIJ";
            string stt = GenerateMD5("15" + barcode + "89e03ef680aa9af3a94724ad2bfbf95a");
            stt = GenerateMD5(stt + "TVosDvuLEetYQ8QeCx4K8J0VhTVEh4Eu");
            string s1 = stt.Substring(0, 1);
            string s2 = stt.Substring(stt.Length - 1, 1);
            int p = "0123456789".IndexOf(s1);
            int p2 = "0123456789".IndexOf(s2);
            if (p > 0)
            {
                s1 = IStr.Substring(p, 1);
            }
            if (p2 > 0)
            {
                s2 = IStr.Substring(p2, 1);
            }
            return (s1 + s2);
        }
        /// <summary>
        /// MD5字符串加密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns>加密后字符串</returns>
        static string GenerateMD5(string txt)
        {
            using (System.Security.Cryptography.MD5 mi = System.Security.Cryptography.MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }

        /// <summary>
        /// 获取机型参数
        /// </summary>
        /// <param name="_L"></param>
        /// <param name="_W"></param>
        /// <param name="_H"></param>
        /// <param name="_SIZE"></param>
        /// <param name="_MERGE_NUM">并箱数</param>
        /// <param name="_LAY_NUM">层数</param>
        /// <param name="_RULER_NUM">下线数</param>
        /// <param name="_HAND_HEIGHT">抱夹高度</param>
        /// <returns></returns>
        static bool GET_MODE_PARAMETER(int _L, int _W, int _H, int _SIZE, out int _MERGE_NUM, out int _LAY_NUM, out int _RULER_NUM, out int _HAND_HEIGHT)
        {
            var _MODE_PARAMETER_CHECK = true;
            _MERGE_NUM = 0;
            _LAY_NUM = 0;
            _RULER_NUM = 0;
            _HAND_HEIGHT = 0;

            //并箱数
            if (_SIZE >= 32 && _SIZE <= 43)
            {
                _MERGE_NUM = ((1050 / _W) / 2) * 2;
            }
            else if (_SIZE >= 45 && _SIZE <= 55)
            {
                _MERGE_NUM = ((1250 / _W) / 2) * 2;
            }
            else if (_SIZE == 58)
            {
                _MERGE_NUM = 1250 / _W;
            }
            else if (_SIZE >= 60 && _SIZE <= 70)
            {
                _MERGE_NUM = 1350 / _W;
            }
            else if (_SIZE >= 75 && _SIZE <= 90)
            {
                _MERGE_NUM = 1350 / _W;
            }
            else
            {
                _MODE_PARAMETER_CHECK = false;
                return _MODE_PARAMETER_CHECK;
            }

            //层数
            if (_SIZE >= 32 && _SIZE <= 43)
            {
                _LAY_NUM = 3;
                _HAND_HEIGHT = _H;
            }
            else if (_SIZE >= 45 && _SIZE <= 75)
            {
                _LAY_NUM = 2;
                _HAND_HEIGHT = _H;
            }
            else if (_SIZE >= 80 && _SIZE <= 90)
            {
                _LAY_NUM = 1;
                _HAND_HEIGHT = _H;
            }
            else
            {
                _MODE_PARAMETER_CHECK = false;
                return _MODE_PARAMETER_CHECK;
            }

            //下线数
            if (_W >= 200)
            {
                _RULER_NUM = 1;
            }
            else
            {
                if (_SIZE <= 55)
                {
                    _RULER_NUM = 2;
                }
                else
                {
                    _RULER_NUM = 1;
                }
            }

            return _MODE_PARAMETER_CHECK;
        }



        public class Student
        {
            public long Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
        }

        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public string Country { get; set; }
        }

        [Measurement("mem")]
        public class Mem
        {
            [Column("host", IsTag = true)] public string Host { get; set; }
            [Column("used_percent")] public double? UsedPercent { get; set; }
            [Column(IsTimestamp = true)] public DateTime Time { get; set; }
        }

        /// <summary>
        /// 类似于关系数据库的表名
        /// </summary>
        [Measurement("pack4")]
        public class packdto
        {
            /// <summary>
            /// 标签
            /// </summary>
            [Column("car", IsTag = true)]
            public string car { get; set; }
            /// <summary>
            /// 普通字段
            /// </summary>
            [Column("money")]
            public double money { get; set; }
            /// <summary>
            /// 普通字段
            /// </summary>
            [Column("temp")]
            public int temp { get; set; }
            /// <summary>
            /// 普通字段--中文值
            /// </summary>
            [Column("tempCn")]
            public string tempCn { get; set; }
            /// <summary>
            /// 创建时间
            /// </summary>
            [Column(IsTimestamp = true)]
            public DateTime Timestamp { get; set; }
        }

        public class ParameterPair
        {
            public string ParamCode { get; set; }
            public string ParamValue { get; set; }

            // 构造函数（可选）
            public ParameterPair(string paramCode, string paramValue)
            {
                ParamCode = paramCode;
                ParamValue = paramValue;
            }

            // 重写ToString方法（可选），以便更容易地查看对象信息
            public override string ToString()
            {
                return $"PARAM_CODE: {ParamCode}, PARAM_VALUE: {ParamValue}";
            }
        }


    }
}
